package rabbit.routing;


import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author 汪洋
 * @Description
 */
public class Routing_Producer {
    //声明一个队列名称
    public final static String QUEUE_NAME_ONE = "routing1";
    public final static String QUEUE_NAME_TWO = "routing2";
    public static void main(String[] args) throws IOException, TimeoutException {
        //1、构建一个连接工厂对象
        ConnectionFactory factory = new ConnectionFactory();
        //2、对该工厂对象进行相关的配置
        factory.setUsername("root");
        factory.setPassword("root");
        factory.setVirtualHost("/pjedu");
        //3、通过该工厂获取到连接对象
        Connection connection = factory.newConnection();
        //4、通过连接对象来获取到频道对象
        Channel channel = connection.createChannel();
        //5、通过隧道来创建交换机对象
        String exchangeName = "routingExchange";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,false,null);
        //6、通过频道对象来创建多个queue队列
        channel.queueDeclare(QUEUE_NAME_ONE, true, false, false, null);
        channel.queueDeclare(QUEUE_NAME_TWO, true, false, false, null);
        //7、交换机和队列进行绑定
        channel.queueBind(QUEUE_NAME_ONE,exchangeName,"error");
        channel.queueBind(QUEUE_NAME_TWO,exchangeName,"error");
        channel.queueBind(QUEUE_NAME_TWO,exchangeName,"info");
        channel.queueBind(QUEUE_NAME_TWO,exchangeName,"warn");
        //8、发送消息,注意,此时的routingKey这个参数需要根据情况来进行改变,它的书写范围就是在绑定交换机和队列时
        //所指定的routingKey
        String message = "Hello info!";
        channel.basicPublish(exchangeName, "info", null, message.getBytes());
        //7、关闭资源
        channel.close();
        connection.close();
    }
}
